// ignore_for_file: constant_identifier_names
import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:junyeyishu/utils/utils.dart';
import 'package:package_info_plus/package_info_plus.dart';

// app 启动
const url_getAppUpgradeInfo = "lua/getAppUpgradeInfo";
const url_getCurtime = "lua/getCurtime";

// 登录模块
const url_captchaToSms = "login/captchaToSms";
const url_login = "login";
const url_password_login = "login/passwdLogin";

// 首页模块
const url_index_getCache = "lua/getCache?key=index";

const url_u_getFriendsList = "u/getFriendsList";
const url_u_getInvitationRule = "u/getInvitationRule";
const url_u_charts = "u/inviteRank";

const url_goods_onSale = "goods/onSale";

const url_goods_calendar = "goods/calendar";
const url_goods_goodsInfo = "goods/goodsInfo";

const url_user_getOpenMysteryboxList = "user/getOpenMysteryboxList";

const url_index_combineEventList = "index/combineEventList";
const url_user_combineEventList = "user/combineEventInfo";
const url_user_getMyCombinelog = "user/getMyCombinelog";
const url_user_combineNft = "user/combineNft";

// 缤纷合成模块
const url_index_randomSynthesisEventList = "index/randomSynthesisEventList";
const url_synthesis_info = "synthesis/info";
const url_synthesis_getMyCombineLog = "synthesis/getMyCombineLog";
const url_synthesis_combineNft = "synthesis/combineNft";

const url_index_getLuckyEventList = "index/getLuckyEventList";
const url_lucky_getInfo = "lucky/getInfo";
const url_lucky_draw = "lucky/draw";
const url_lucky_getDrawLogList = "lucky/getDrawLogList";

const url_user_getMySystemoticelist = "user/getMySystemNoticeList";

const url_index_disassembleEventList = "index/disassembleEventList";
const url_user_disassembleEventInfo = "user/disassembleEventInfo";
const url_user_disassembleNft = "user/disassembleNft";
const url_index_getDisassembleLog = "index/getDisassembleLog";
const url_user_getDisassemblelog = "user/getDisassemblelog";

const url_groupNote_getGroupNoteList = "groupNote/getGroupNoteList";
const url_groupNote_getGroupNoteInfo = "groupNote/getGroupNoteInfo";
const url_groupNote_joinGroupNote = "groupNote/joinGroupNote";

// 寄售模块
const url_index_seriesList = "lua/getCache?key=seriesList";
 const url_market_mySeriesList = "market/mySeriesList";
const url_market_getMyAndOtherSeriesList = "market/getMyAndOtherSeriesList";
const url_market_manageMySeries = "market/manageMySeries";

// const url_index_consignmentList = "index/consignmentList";
const url_index_consignmentList = "index/newConsignmentList";

const url_market_collectionList = 'market/collectionList';
const url_market_collectionInfo = "market/collectionInfo";
const url_market_consignRecord = "market/consignRecord";

const url_market_tradeLogList = "market/tradeLogList";
const url_market_tradeCount = 'market/tradeCount';

const url_market_onShelf = "market/onShelf";
const url_market_offShelf = "market/offShelf";
const url_market_isPayPwd = "market/hasTradePasswd";
const url_market_isCidentity = "market/isCidentity";

//寄售订单列表
const url_market_orderList = "market/orderList";
const url_market_cancelOrder = "market/cancelOrder";
const url_market_rePayOrder = "market/rePayOrder";

const url_market_payOrder = "market/payOrder";

const url_market_repidPayOrder = "market/rapidPayOrder";

const url_market_haveBatchBuy = 'market/haveBatchBuy';
const url_market_batchBuy = 'market/batchBuy';
const url_market_batchOrderList = 'market/batchOrderList';
const url_market_rePayBatchOrder = 'market/rePayBatchOrder';
const url_market_cancelBatchOrder = 'market/cancelBatchOrder';

const url_market_onShelfBatch = 'market/onShelfBatch';
const url_market_offShelfBatch = 'market/offShelfBatch';
const url_market_haveBatchShelf = 'market/haveBatchShelf';

// 求购模块
const url_ask_addOrder = "ask/addOrder";
const url_entrust_addOrder = "entrust/addOrder";

const url_ask_orderList = "ask/orderList";
const url_entrust_orderList = "entrust/orderList";


const url_ask_pickOrder = "ask/pickOrder";
const url_entrust_pickOrder = "entrust/pickOrder";


const url_ask_getMyOrderList = "ask/getMyOrderList";
const url_entrust_getMyOrderList = "entrust/getMyOrderList";

const url_ask_cancelOrder = "ask/cancelOrder";
const url_ask_dealLog = "ask/dealLog";
const url_ask_curList = "ask/curList";
const url_ask_getMySellOrderList = "ask/getMySellOrderList";

// 公告模块
const url_anno_categ = "lua/getCache?key=announcementCategories";
const url_anno = "lua/getAnnouncementList";
const url_anno_aboutGoods = "anno_aboutGoods";

// 汇付模块
const url_hf_checkHuifuUser = 'huifu/queryWallet';
const url_hf_manageWallet = 'huifu/manageWallet';
const url_hf_walletFeeOrder = 'huifu/generateRegWalletFeeOrder';
const url_hf_openWallet = 'huifu/regWallet';
const url_hf_checkHuifuFee = 'huifu/queryRegWalletFee';
const url_huifu_generateOrder = "huifu/generateOrder";
const url_huifu_repay = "huifu/rePayOrder";

// 我的模块
const url_user_orderList = 'user/orderList';
const url_user_getMyNftInfo = 'user/getMyNftInfo';

const url_user_nftList = 'user/getMyNftList';
const url_user_getMyNftListByGoods = 'user/getMyNftListByGoods';

const url_user_openMysterybox = 'user/openMysterybox';
const url_user_givePresent = 'user/givePresent';
const url_user_getMyPresentList = 'user/getMyPresentList';

// 设置
const url_u_getMergedUserInfo = 'u/getMergedUserInfo';
const url_u_factorAuthenticate = 'u/factorAuthenticate';
const url_u_modifyNickname = 'u/modifyNickname';
const url_u_modifyAvatar = 'u/modifyAvatar';
const url_u_modifyShippingAddress = 'u/modifyShippingAddress';
const url_u_cancelAccount = 'u/cancelAccount';
const url_u_modifyDealPassword = 'u/modifyDealPassword';
const url_u_modifyLoginPasswd = 'u/modifyLoginPasswd';

class NetworkResp {
  bool success;
  String msg;
  dynamic data;
  dynamic ret;
  NetworkResp({this.success = false, this.msg = "", this.data});

  @override
  String toString() {
    return "success:$success  msg:$msg  data:$data";
  }
}

var outputEncoder = const JsonEncoder.withIndent('  ');

class Network {
  static bool test = false;

  static String? version;

  // 判断使用哪个域名
  static get baseURL {
    return test ? "https://ccapi.wexiang.vip/" : "https://ccapi.wexiang.vip/";
  }

  static get h5URL {
    return test ? "https://cch5.wexiang.vip/" : "https://cch5.wexiang.vip/";
  }

  static Dio dio = Dio(
    BaseOptions(
      contentType: Headers.formUrlEncodedContentType,
      connectTimeout: const Duration(seconds: 10),
      sendTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    ),
  );
  static Dio rtdio = Dio(
    BaseOptions(
      contentType: Headers.formUrlEncodedContentType,
      connectTimeout: const Duration(seconds: 2),
      sendTimeout: const Duration(seconds: 2),
      receiveTimeout: const Duration(seconds: 2),
    ),
  );

  static Future<NetworkResp> request(method, String url,
      {param, data, key}) async {
    var now = DateTime.now();
    var timestamp = (now.millisecondsSinceEpoch / 1000).truncate();

    if (version == null) {
      var packageInfo = await PackageInfo.fromPlatform();
      version = packageInfo.version;
    }

    // 请求头
    var header = {
      "timestamp": timestamp,
      "sign": getSign(now),
      "token": User.current?.token ?? "",
      "v": version,
      "tsig": getTSig(timestamp),
    };

    final resp = NetworkResp();

    var base = baseURL;

    // url做过滤
    // if (url.startsWith("lua")) {
    //   // url.startsWith("getAppUpgradeInfo") ||
    //   // url.startsWith("getCurtime") ||
    //   // url.startsWith("getAnnouncementList"))
    //   base = cacheBaseURL;
    // }

    url = "$base$url";
    try {
      var ret;
      if (url.contains(url_groupNote_getGroupNoteInfo)) {
        ret = await rtdio.request(url,
            queryParameters: param,
            data: data,
            options: Options(method: method, headers: header));
      } else {
        ret = await dio.request(url,
            queryParameters: param,
            data:data,
            options: Options(method: method, headers: header));
      }

      dynamic res = ret.data;
      if (res is String) {
        res = jsonDecode(res);
      }

      resp.ret = res;

      if (res?["code"] == 0 || res?["status"] == 200) {
        resp.success = true;
        resp.msg = "${res["message"] ?? res["msg"]}";
        resp.data = res[key];

        log("----------------------------->");
        log(url);
        log((data ?? param).toString());
        log(outputEncoder.convert(res));
      } else if (res?["code"] == -1) {
        User.logout();
        resp.msg = res["msg"];
        log("----------------------------->");
        log(url);
        log((data ?? param).toString());
        log(res.toString());
      } else if (res is Map && res["msg"] != null) {
        resp.msg = res["msg"];

        log("----------------------------->");
        log(url);
        log((data ?? param).toString());
        log(res.toString());
      }
    } catch (e) {
      log("----------------------------->");
      log(url);
      log((data ?? param).toString());
      log(e.toString());

      if (e is DioError) {
        if (e.response != null) {
          int statusCode = e.response!.statusCode!;

          if (statusCode >= 400 && statusCode < 500) {
            // 处理 4xx 错误状态码
            resp.success = false;
            resp.msg = "请求过于频繁，请稍后访问。如需立即解封，请联系管理员。";
          } else {
            resp.success = false;
            resp.msg = "网络不佳，请稍候再试";
          }
        } else {
          resp.success = false;
          resp.msg = "网络不佳，请稍候再试";
        }
      } else {
        resp.success = false;
        resp.msg = "网络不佳，请稍候再试";
      }

      return resp;
    }

    return resp;
  }

  static Future<NetworkResp> get(url,
      [queryParameters, dataKey = "data"]) async {
    return request("get", url, param: queryParameters, key: dataKey);
  }

  static Future<NetworkResp> post(url,
      {data, context, dataKey = "data"}) async {
    var ctx;
    if (context != null) {
      showDialog(
          barrierDismissible: false,
          context: context,
          builder: (context) {
            ctx = context;
            return const Center(
                child: CircularProgressIndicator(color: Colors.white));
          });
    }

      

    final ret = await request("post", url, data:data, key: dataKey);

    if (context != null && ctx == null) {
      await Future.delayed(const Duration(milliseconds: 300));
    }

    if (ctx != null) {
      Navigator.of(ctx).pop();
    }

    return ret;
  }
}
